#!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""
@File    :   is_dns.py    
@Contact :   291622538@qq.com

@Modify Time      @Author    @Version    @Description
------------      -------    --------    -----------
2021/4/5 13:50   fan        1.0         None
"""
import csv
import os
import time


def dig_cmd(ip, domain_name):
    cmd = "dig @%s +short %s MX" % (ip, domain_name)
    f = os.popen(cmd)
    return f


def is_dns(ip):
    f = dig_cmd(ip, "baidu.com")
    lines = f.readlines()
    print(lines[-1])
    if "connection timed out" in lines[-1]:
        return False
    else:
        return True


if __name__ == '__main__':

    s_time = time.time()

    is_open_result = []

    with open('data/IP.csv', 'r', encoding='UTF-8-sig') as f:

        for num, line in enumerate(csv.reader(f)):

            if num == 0:
                is_open_result.append([line[0], line[1], line[2], "是否是域名服务器"])
                continue

            if num == 10:
                break

            # print(line)
            ip = line[0]
            location = line[1]
            in_or_out = line[2]
            result = is_dns(ip)
            print(result)
            # print(result)

            is_open_result.append([ip, location, in_or_out, result])
    # print(is_open_result)

    with open('data/IP-result.csv', 'w', encoding='utf-8', newline='') as f:
        writer = csv.writer(f)

        writer.writerows(is_open_result)

    e_time = time.time()

    print("scan time is ", e_time - s_time)
    print("结束的时间：", e_time)
